package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.coretools.AppleAuthTools;
import com.ruoyi.system.coretools.GoogleAuthTools;
import com.ruoyi.system.domain.TUserInfo;
import com.ruoyi.system.domain.dto.TUserInfoDto;
import com.ruoyi.system.service.ITUserInfoService;
import com.ruoyi.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 苹果三方登录
 *
 * @author ruoyi
 * @date 2024-04-23
 */
@RestController
@RequestMapping("/system/apple")
public class AppleAuthController extends BaseController {
    @Autowired
    AppleAuthTools appleAuthTools;
    @Resource
    private TokenService tokenService;
    @Autowired
    UserService userService;

    @Resource
    private ITUserInfoService userInfoService;
    @Autowired
    SysRegisterService sysRegisterService;

    /**
     * google login
     */
    @GetMapping("/appleLogin")
    public AjaxResult googleLogin(@RequestParam(name = "idTokenString", defaultValue = "") String idTokenString, @RequestParam(name = "userId", defaultValue = "") String userId) throws Exception {
        logger.info("收到apple验证登录请求，客户端从apple那边拿过来的idTokenString:{} userId:{}", idTokenString, userId);

        //先验证apple那边的信息(获取到邮箱，没有邮箱就只有用openID,先设为邮箱做业务逻辑)
        String email = appleAuthTools.appleVerify(idTokenString, userId);

        //再判断在平台是否有账号，有账号直接登录拿平台内通用token，没账号注册登录拿平台内通用token
        TUserInfo result = null;

        TUserInfo info = null;
        if (StringUtils.isNotEmpty(email)) {
            info = userInfoService.selectByEmail(email);
        }
        if (Objects.isNull(info)) {
            //多走个自动注册流程
            sysRegisterService.appleNewUserAutoRegister(email);

        }

        //走自动平台登录流程
        //准备好后把参数传给系统内部的注册接口后登录接口返回token
        TUserInfoDto tUserInfoDto = new TUserInfoDto();
        //tUserInfoDto.setVipId(userId);
        tUserInfoDto.setUserEmail(email);
        //登录
        result = userService.userLoginByApple(tUserInfoDto);


        String appToken = tokenService.createAppToken(result);
        //google idTokenString换平台token
        logger.info("结束apple三方登录请求:{}", result);
        return AjaxResult.success(appToken);
    }

}
